#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______   _______   _______  #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \ |       \ |   ____|  #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  ||  .--.  ||  |__      #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  ||  |  |  ||   __|      #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  ||  '--'  ||  |____      #
#|__|     | _| `._____||_______||_______| \______| \______/ |_______/ |_______|    #
#                                                                                 #
#                                Channel Core                                    #
#                             Circuits FrameWork                                #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
from circuits.core import listener, Event, Component

# Sets plugin variables
__id__ = "channels"
__core__ = True

# Creates event classes
class IRCjoin(Event): pass
class IRCpart(Event): pass
class IRCmessage(Event): pass
class IRCnames(Event): pass
class TellReply(Event): pass

class Channels(Component):

	def __init__(self, *args, **kwargs):
		# Important: Call the super constructors to initialize the Component.
		super(Network, self).__init__(*args, **kwargs)
		self.channel = kwargs["channel"]
		kwargs["cursor"].execute("SELECT channame FROM channels WHERE netid = %s AND active = 1", (self.channel.strip("Net"))
		data = kwargs["cursor"].fetchall()
		self.channels = {}
		for row in data:
			self.push(IRCjoin(row[0]), "issue-join", self.channel)
			self.channels[row[0]] = Channel(row[0])
	
	@listener("command-join")	
	def join(self, **kwargs):
		# Checks botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
		
				# Joins the channel
				self.push(IRCjoin(kwargs["command"][1]), "issue-join", self.channel)
				self.channels[kwargs["command"][1]] = Channel(kwargs["command"][1])
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
			
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
	
	@listener("command-part")	
	def part(self, **kwargs):
		# Checks botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
		
				# Checks if a message is given
				if len(kwargs["command"]) > 2:
					qmessage = kwargs["command"][2:]
				else:
					qmessage = "MeatBallBot is parting."
		
				# Parts the channel
				self.push(IRCpart(kwargs["command"][1], qmessage), "issue-part", self.channel)
				if kwargs["command"][1] in self.channels:
					del self.channels[kwargs["command"][1]
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
			
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
	
	@listener("command-alljoin")	
	def alljoin(self, **kwargs):
		# Checks botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
			
				# Joins all channels
				kwargs["cursor"].execute("SELECT channame FROM channels WHERE netid = %s AND active = 1", (self.channel.strip("Net"))
				data = kwargs["cursor"].fetchall()
				self.channels = {}
				for row in data:
					self.push(IRCjoin(row[0]), "issue-join", self.channel)
					self.channels[row[0]] = Channel(row[0])
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
			
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
	
	@listener("command-allpart")	
	def allpart(self. **kwargs):
		# Checks botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
		
				# Checks if a message is given
				if len(kwargs["command"]) > 2:
					qmessage = kwargs["command"][2:]
				else:
					qmessage = "MeatBallBot is parting."
		
				# Parts all channels
				for channel in self.channels.keys():
					self.push(IRCpart(channel, qmessage), "issue-part", self.channel)
					del self.channels[channel]
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
			
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
		
class Channel(Component):
	
	def __init__(self, channel):
		self.channel = channel
		self.push(IRCnames(channel), "issue-names", self.channel)
		
	@listener("numeric-***")
	def namereply(self, **kwargs):
		pass
	
	# Updates nick in names on nick	
	@listener("relay-nick")
	def nick(self, source, newnick, ctime):
		source = source.split("!")[0]
		host = self.names[source]
		del self.names[source]
		self.names[newnick] = host
	
	# Adds nick on join
	@listener("relay-join")	
	def join(self, source, channel):
		host = source.split("@")[1]
		ident = source.split("@")[0].split("!")[1]
		source = source.split("!")[0]
		self.names[source] = (ident, host)
	
	# Removes nick on part
	@listener("relay-part")	
	def part(self, source, channel, message):
		host = source.split("@")[1]
		ident = source.split("@")[0].split("!")[1]
		source = source.split("!")[0]
		del self.names[source]
	
	# Removes nick on quit	
	@listener("relay-quit")	
	def quit(self, source, message):
		host = source.split("@")[1]
		ident = source.split("@")[0].split("!")[1]
		source = source.split("!")[0]
		del self.names[source]
	
	# Responds to queries for (ident, host) or nick, defaults to replying with names list	
	@listener("chan-tell")
	def onTELL(self, nick=None, ident=None, host=None):
		if nick is not None:
			if nick in self.names:
				reply = self.names[nick]
			else:
				reply = None
				
		elif host is not None and ident is not None:
			if (ident, host) in self.names.values():
				for item in self.names.items():
					if (ident, host) == item[1]:
						reply = item[0]
			else:
				reply = None
						
		else:
			reply = self.names
		self.push(TellReply(reply), "chan-tell-reply", self.channel)
		
def startup(channel, cursor):
	plugin = Channels(channel = channel, cursor = cursor)
	return (__id__, plugin)

def kill():
	return __id__
